let express = require('express')
let router = express.Router()
let mongoose = require('mongoose');
let jsonwebtoken = require('jsonwebtoken');
require('../util/authConfig')
//登录
router.post('/login', async function (req, resp) {
    let { phone, password } = req.body;
    let re = await mongoose.model('studentsModel').find({
        phone:phone
    }); 
    let re2 = await mongoose.model('studentsModel').find({
        phone:phone,
        password:password
    }); 
    console.log(re2);
    if (re.length > 0) {
        if(re2.length > 0){
            let token = jsonwebtoken.sign({
                user: re[0]
            }, 'star', {
                expiresIn: 36000
            })
            // console.log(token)
            resp.send({
                code: 1,
                message: '登录成功!',
                data: token,
                data2:re2
            });
        }else{
            resp.send({
                code: 3,
                message: '密码有误!'
            });
        }


    } else {
        resp.send({
            code: 2,
            message: '账号不存在!'
        });
    }
})

//注册
router.post('/register',async function (req, resp) {
    // console.log(req.body);
    //获取注册账号和密码
    let { phone, password } = req.body;
    //判断账号是否存在
    // let re = userInfor.some(function (u) {
    //     return u.acc == name;
    // });
    let re = await mongoose.model('studentsModel').find({
        phone:phone,
        
    });
    console.log(re) 
    if (re) {
        await mongoose.model('studentsModel').create({
            name:'王小明',
            phone:phone,
           password:password,
           gender:'女',
           avatar:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202107%2F09%2F20210709142454_dc8dc.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666778921&t=140c865c6e88010cb05838d4bab86918'
        });
        resp.send({
            code: 1,
            message: '注册成功!请登录！'
        });
    } else {
        resp.send({
            code: 2,
            message: '注册失败!账号已经存在'
        });
    }
});

// router.post('/demo', function (req, resp) {
//     // resp.send({
//     //     code:1,
//     //     message:'注册成功!'
//     // });
//     let auth = req.header('Authorization');
//     let token = auth.replace('Bearer ', '');
//     let userObj = jsonwebtoken.verify(token, 'star').user;
//     resp.send({
//         data:userObj
//     })

// });



module.exports = router